#pragma once

#include <iostream>
#include <vector>
#include <unordered_map>
#include <assert.h>
#include <fstream>

#include <mysql/mysql.h>
// #include "include/mysql.h"
#include "../comm/util.hpp"
#include "../comm/log.hpp"
#include "../SqlPool/sqlconnPool.hpp"

// 根据题目 list 文件,加载所有的题目信息到内存中
// model : 主要用来和数据进行交互

namespace ns_model
{

    // 题目信息
    class Question
    {
    public:
        std::string number; // 题目编号,唯一
        std::string title;  // 题目标题
        std::string star;   // 难度:简单 中等 困难
        int cpu_limit;      // 时间要求
        int mem_limit;      // 空间要求 (kb)
        std::string desc;   // 题目的描述 (discribe)
        std::string header; // 题目预设给用户的在线编辑器的代码 (Leetcode) 中给出的接口
        std::string tail;   // 题目的测试用例,需要和header 拼接,形成完整代码
        int success_count;
        std::string data_range;
    };

    class Model
    {
    private:
        // 题号
        std::unordered_map<std::string, Question> questions;

        ns_sqlconnpool::SqlConnPool *_SqlConnPool = nullptr;

        const std::string oj_questions = "questions";
        const std::string host = "192.168.5.12";
        const std::string user = "oj_client";
        const std::string password = "123456";
        const std::string database = "oj";
        const int port = 3306;

    public:
        Model()
        {
           
            _SqlConnPool = ns_sqlconnpool::SqlConnPool::GetInstance(host, port, user, password, database);
            
        }
        ~Model() {}

        bool QueryMysql(const std::string &sql, std::vector<ns_model::Question> *out)
        {
            // 创建 mysql 句柄
            // MYSQL *my = mysql_init(nullptr);

            // if (mysql_real_connect(my, host.c_str(), user.c_str(), password.c_str(), database.c_str(), port, nullptr, 0) == nullptr)
            // {
            //     // 连接失败
            //     // mysql_error(my);
            //     ns_log::lg.LogMessage(ns_log::Fatal, "连接数据库失败\n");
            //     return false;
            // }
            // ns_log::lg.LogMessage(ns_log::Info, "连接数据库成功\n");

            // // ! 一定要设置编码格式
            // mysql_set_character_set(my, "utf8");

            // // 执行 sql 语句
            // if (mysql_query(my, sql.c_str()) != 0)
            // {
            //     // 访问失败
            //     ns_log::lg.LogMessage(ns_log::Warning, "数据库 执行失败\n");
            //     return false;
            // }

            std::shared_ptr<SqlConn> conn = _SqlConnPool->Get_Conn();

            // 提取结果
            MYSQL_RES *res = conn->query(sql);
            if (res == nullptr)
            {
                // 访问失败
                ns_log::lg.LogMessage(ns_log::Warning, "数据库 执行失败\n");
                return false;
            }
            ns_log::lg.LogMessage(ns_log::Info, "sql success !\n");
            //std::cout << sql << std::endl;
            // 分析结果
            int rows = mysql_num_rows(res);   // 获得行数量
            int cols = mysql_num_fields(res); // 获得列数量

            ns_model::Question q;

            for (int i = 0; i < rows; i++)
            {
                //  定义 row ,等于查出出来的每一行

                /*

                CREATE TABLE IF NOT EXISTS `questions`(
                (number)  id int PRIMARY KEY AUTO_INCREMENT COMMENT '题目的ID',
                title VARCHAR(64) NOT NULL COMMENT '题目的标题',
                star VARCHAR(8) NOT NULL COMMENT '题目的难度',
                question_desc TEXT NOT NULL COMMENT '题目描述',
                header TEXT NOT NULL COMMENT '题目头部，给用户看的代码',
                tail TEXT NOT NULL COMMENT '题目尾部，包含我们的测试用例',
                time_limit int DEFAULT 1 COMMENT '题目的时间限制',
                mem_limit int DEFAULT 5000000 COMMENT '题目的空间限制'
                )ENGINE=INNODB DEFAULT CHARSET=utf8;

                 */

                MYSQL_ROW row = mysql_fetch_row(res);
                q.number = row[0];
                q.title = row[1];
                q.star = row[2];
                q.desc = row[3];
                q.header = row[4];
                q.tail = row[5];
                q.cpu_limit = atoi(row[6]);
                q.mem_limit = atoi(row[7]);

                int try_count = atoi(row[8]), success_counts = atoi(row[9]);
                q.success_count = try_count ? success_counts * 100 / try_count:0;

                q.data_range = row[10];

                out->push_back(q);
            }

            // 释放结果空间
            // free(res);

            return true;
        }

        // 获取所有的题目列表
        bool GetAllQuestionList(std::vector<Question> *out)
        {
            std::string sql = "select * from ";
            sql += oj_questions;
            sql += ";";
            return QueryMysql(sql, out);
        }

        // 获取指定的一道题目
        bool GetOneQuestion(const std::string &number, Question *q)
        {
            bool res = false;

            std::string sql = "select * from ";
            sql += oj_questions;
            sql += " where id = ";
            sql += number;
            sql += " ;";

            std::vector<ns_model::Question> result;
            if (QueryMysql(sql, &result))
            {
                if (result.size() == 1)
                {
                    *q = result[0];
                    res = true;
                }
            }
            return true;
        }

        // 增加提交次数
        bool Add_Try_count(const std::string &number)
        {

            std::string sql = "update " + oj_questions + " set try_count = try_count + 1 where id = " + number;

            std::shared_ptr<SqlConn> conn = _SqlConnPool->Get_Conn();

            return conn->update(sql);
        }

        bool Add_Success_count(const std::string &number)
        {

            std::string sql = "update " + oj_questions + " set success_count = success_count + 1 where id = " + number;

            std::shared_ptr<SqlConn> conn = _SqlConnPool->Get_Conn();

            return conn->update(sql);
        }
    };
}
